<template>
  <div class="goods-box" @click="handleToGoods(goodsId)">
    <van-image :src="image" class="goods-image" width="80%"></van-image>
    <span class="goods-name">{{ name }}</span>
    <div class="goods-price">
      <span>￥{{ price }}</span>
      <van-icon
        name="cart-circle-o"
        size="24"
        color="red"
        @click.stop="handleAddToCart"
      />
    </div>
  </div>
</template>
<script>
import { defineComponent } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { Toast } from 'vant'
export default defineComponent({
  props: {
    image: String,
    name: String,
    price: [String, Number],
    goodsId: [String, Number]
  },
  setup(props) {
    const router = useRouter()
    const store = useStore()
    const handleToGoods = (goodsId) => {
      router.push({ name: 'goods', query: { goodsId } })
    }
    const handleAddToCart = () => {
      const goodsInfo = {
        ID: props.goodsId,
        NAME: props.name,
        PRESENT_PRICE: props.price,
        IMAGE1: props.image
      }
      if (store.getters.cartInfo.length === 0) {
        store.dispatch('cart/addGoodsToCart', goodsInfo)
        Toast.success('添加成功')
      } else {
        let isHaveGoods = store.getters.cartInfo.find(
          (cart) => cart.goodsId == props.goodsId
        )
        if (!isHaveGoods) {
          store.dispatch('cart/addGoodsToCart', goodsInfo)
          Toast.success('添加成功')
        } else {
          Toast.fail('已有此商品')
        }
      }
    }
    return {
      handleToGoods,
      handleAddToCart
    }
  }
})
</script>
<style lang="scss" scoped>
.goods-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  padding: 20px;
  margin-bottom: 10px;
  border-radius: 10px;
  box-shadow: 0 0 10px #efefef;
  .goods-name {
    font-size: 14px;
    height: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
  .goods-price {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    span {
      color: red;
    }
  }
}
</style>